package com.bishe.demo.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ViewMappingInterceptor implements HandlerInterceptor {
    private final static Logger LOGGER = LoggerFactory.getLogger(ViewMappingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOGGER.debug("==== preHandle ====");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        LOGGER.debug("==== postHandle ====");
        //排除转发和重定向，接口返回
        if (modelAndView != null && !modelAndView.getViewName().startsWith("redirect") && !modelAndView.getViewName().startsWith("forward")) {
            //判断ModelMap中是否设置有template
            ModelMap modelMap = modelAndView.getModelMap();
            if (StringUtils.isBlank((String) modelMap.get("template"))) {
                //获取path路径
                String servletPath = request.getServletPath();
                if (servletPath.startsWith("/")) {
                    servletPath = servletPath.substring(1);
                }
                modelMap.put("template", servletPath);
            }
        }else {
            HandlerInterceptor.super.postHandle(request, response, handler,modelAndView);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LOGGER.debug("==== afterCompletion ====");
    }
}
